//
//  PublishViewController.m
//  MainUI
//
//  Created by xalo on 16/5/2.
//  Copyright © 2016年 赵言. All rights reserved.
//

#import "PublishViewController.h"
#import "MainModel.h"

@interface PublishViewController () <UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (strong, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) IBOutlet UIView *contentView;
@property (strong, nonatomic) IBOutlet UITextField *mainTitle;
@property (strong, nonatomic) IBOutlet UITextField *subtitle;
@property (assign, nonatomic)CGPoint point;
@property (strong, nonatomic)NSMutableArray *array;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *topLine;

@end

@implementation PublishViewController

static double height = 0;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.rightBarButtonItem = ({
        
        UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"发表" style:(UIBarButtonItemStylePlain) target:self action:@selector(rightBarBtnAction:)];
        btn;
    });
    
    self.textView.scrollEnabled = YES;
    self.textView.contentInset = UIEdgeInsetsMake(3, 0, 0, 0);
    
    //添加监听，监听键盘的弹出和回收（系统提供的）
    //键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘回收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 键盘事件的监听回调方法
//键盘弹出
- (void)keyboardShow:(NSNotification *)notifi{
    
    self.topLine.constant = -10;
}
//键盘回收
- (void)keyboardHidden:(NSNotification *)notifi{
    
    self.topLine.constant = 64;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 右按钮方法
- (void)rightBarBtnAction:(UIBarButtonItem *)sender {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendValue)]) {
        
        [self.delegate sendValue];
    }
    
    //数据网络存储
    AVObject *object = [AVObject objectWithClassName:@"Memory"];
    [object setObject:self.mainTitle.text forKey:@"title"];
    [object setObject:self.subtitle.text forKey:@"subtitle"];
    [object setObject:self.textView.text forKey:@"content"];
    [object setObject:[AVUser currentUser].username forKey:@"userName"];
    AVFile *file = [AVFile fileWithName:@"image.png" data:[self makeImageToData:self.imageView.image]];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            
            [object setObject:file.url forKey:@"image"];
            [object saveEventually:^(BOOL succeeded, NSError *error) {
                
                if (succeeded) {
                    
                    NSLog(@"文件保存成功");
                }
                else {
                    
                    NSLog(@"文件保存失败%@",error);
                }
            }];
        }
        else {
            
            NSLog(@"图片保存失败%@",error);
        }
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextView相关
- (CGSize)getStringRectInTextView:(NSString *)string textView:(UITextView *)textView {
    
    //实际textView显示时我们设定的宽
    CGFloat contentWidth = CGRectGetWidth(textView.frame);
    //但事实上内容需要除去显示的边框值
    CGFloat broadWidth = (textView.contentInset.left + textView.contentInset.right + textView.textContainerInset.left + textView.textContainerInset.right + textView.textContainer.lineFragmentPadding/*左边距*/ + textView.textContainer.lineFragmentPadding/*右边距*/);
    CGFloat broadHeight  = (textView.contentInset.top + textView.contentInset.bottom + textView.textContainerInset.top + textView.textContainerInset.bottom);
    //由于求的是普通字符串产生的Rect来适应textView的宽
    contentWidth -= broadWidth;
    
    CGSize InSize = CGSizeMake(contentWidth, MAXFLOAT);
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = textView.textContainer.lineBreakMode;
    NSDictionary *dic = @{NSFontAttributeName:textView.font, NSParagraphStyleAttributeName:[paragraphStyle copy]};
    
    CGSize calculatedSize =  [string boundingRectWithSize:InSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    
    CGSize adjustedSize = CGSizeMake(ceilf(calculatedSize.width),calculatedSize.height + broadHeight);
    return adjustedSize;
}

- (void)textViewDidChange:(UITextView *)textView {
    
    CGSize size = [self getStringRectInTextView:textView.text textView:textView];
    
    if (size.width >= self.textView.bounds.size.width-40 && height < size.height ) {
        
        height = size.height;
        textView.contentOffset = CGPointMake(0, height-10);
        self.point = textView.contentOffset;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    textView.contentOffset = CGPointMake(0, 0);
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    textView.contentOffset = self.point;
}

#pragma mark - 相片
- (IBAction)tapImage:(UITapGestureRecognizer *)sender {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    picker.allowsEditing = YES;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

//相册的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *selectImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.imageView.image = selectImage;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 工具方法
//UIImage转换NSData
- (NSData *)makeImageToData:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 2.0);
    return imageData;
}

//NSData转换为UIImage
- (UIImage *)makeDataToImage:(NSData *)data{
    
    UIImage *image = [UIImage imageWithData:data];
    return image;
}

//键盘回收
- (IBAction)tapAction:(UITapGestureRecognizer *)sender {
    
    [self.textView resignFirstResponder];
}

//警示框
- (void)alertController:(NSString *)alertContent{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:alertContent preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:sureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 懒加载
- (NSMutableArray *)array {
    
    if (!_array) {
        
        _array = [NSMutableArray array];
    }
    return _array;
}
@end
